/**
 * web2010_admin
 * cn.aresoft.web.action.system.user UserAction.java
 */
package com.xsoft.web.action;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.xsoft.framework.po.Result;
import com.xsoft.framework.po.Result2;
import com.xsoft.framework.util.EncryptUtil;
import com.xsoft.framework.util.Page;
import com.xsoft.framework.web.BasicAction;
import com.xsoft.logic.dao.CommonDao;
import com.xsoft.logic.model.DevUsers;
import com.xsoft.logic.model.TdAd;
import com.xsoft.logic.model.TdApple;
import com.xsoft.logic.service.interfaces.UserService;
import com.xsoft.web.util.AppUtils;


/**
 * @author 潘冬 2010-8-10 上午10:00:06
 */
public class UserAction extends BasicAction {
	private static final long serialVersionUID = -160603489017471550L;
	private UserService userService; //也可以加载其他.xml的对应的sql
	private CommonDao commonDao ;
	private DevUsers vo = new DevUsers();
	private List<DevUsers> devUserList ;
	
	
	
	/////////////////////////////////////// 以下方法是给张敏杰临时用的
	
	
	private TdApple tdApple;
	private TdAd tdAd;
	
	public String init(){
		
		String uuid = getFilterParameter(request, "uuid");
		String idfa = getFilterParameter(request, "idfa");
		
		ArrayList list = (ArrayList)commonDao.find("from TdApple where uuid=? and idfa=? ", new Object[]{uuid,idfa});
		if(list!=null && list.size()>0){
			HashMap data = new HashMap();
			data.put("auth",((TdApple)list.get(0)).getAuthToken());
			writeJson(new Result2(0,"ok",data));
			return null;
		}
		
		
		String appKey = getFilterParameter(request, "appKey");
		String sdkVer = getFilterParameter(request, "sdkVer");
		String sdkType = getFilterParameter(request, "sdkType");
		String deviceType = getFilterParameter(request, "deviceType");
		String deviceModel = getFilterParameter(request, "deviceModel");
		String resolution = getFilterParameter(request, "resolution");
		String os = getFilterParameter(request, "os");
		String osVer = getFilterParameter(request, "osVer");
		String isJailbroken = getFilterParameter(request, "isJailbroken");
		String network = getFilterParameter(request, "network");
		String carrier = getFilterParameter(request, "carrier");
		String bId = getFilterParameter(request, "bId");
		String bdname = getFilterParameter(request, "bdname");
		
		String appVer = getFilterParameter(request, "appVer");
		String appBuild = getFilterParameter(request, "appBuild");
		String timezone = getFilterParameter(request, "timezone");
		
		String authToken = UUID.randomUUID().toString().replaceAll("-", "");
		
		
		tdApple = new TdApple( uuid,  idfa,  appKey,  sdkVer,
				 sdkType,  deviceType,  deviceModel,
				 resolution,  os,  osVer,  isJailbroken,
				 network,  carrier,  bId,  bdname,
				 appVer,  appBuild,  timezone,  authToken);
		
		
		//模拟100个广告Id
		Random rd  = new Random();
		tdAd = new TdAd(rd.nextInt(100), bId,  1,  authToken,"0");
		
		commonDao.save(tdApple);
		commonDao.save(tdAd);
		
		HashMap data = new HashMap();
		data.put("auth",authToken);
		
		writeJson(new Result2(0,"ok",data));
		return null;
	}
	
	
	
	public String getAd(){
		
		String auth = getFilterParameter(request, "auth");
		
		ArrayList list = (ArrayList)commonDao.find("from TdAd where authtoken=? ", new Object[]{auth});
		if(list!=null && list.size()>0){
			HashMap data = new HashMap();
			
			TdAd ad = (TdAd)list.get(0);
			
			data.put("adId",ad.getAdId());
			data.put("gameId",ad.getGameId());
			data.put("channelId",ad.getChannelId());
			data.put("url",request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/td.jsp?adid="+ad.getAdId());
			
			writeJson(new Result2(0,"ok",data));
			return null;
		}
		
		writeJson(new Result2(-1,"error","auth验证失败"));
		return null;
	}
	
	//浏览
	public String getAdInfo(){
		
		String auth = getFilterParameter(request, "auth");
		String adId = getFilterParameter(request, "adId");
		String gameId = getFilterParameter(request, "gameId");
		String channelId = getFilterParameter(request, "channelId");
		
		ArrayList list = (ArrayList)commonDao.find("from TdAd where authtoken=? ", new Object[]{auth});
		if(list!=null && list.size()>0){
			TdAd ad =(TdAd) list.get(0);
			ad.setState("1");
			commonDao.save(ad);
			
			
			HashMap data = new HashMap();
			writeJson(new Result2(0,"ok",data));
			return null;
		}
		
		writeJson(new Result2(-1,"error","auth验证失败"));
		return null;
	}
	
	
	//下载
	public String downloadApp(){
		String auth = getFilterParameter(request, "auth");
		String adId = getFilterParameter(request, "adId");
		String gameId = getFilterParameter(request, "gameId");
		String channelId = getFilterParameter(request, "channelId");
		
		ArrayList list = (ArrayList)commonDao.find("from TdAd where authtoken=? ", new Object[]{auth});
		if(list!=null && list.size()>0){
			TdAd ad =(TdAd) list.get(0);
			ad.setState("2");
			commonDao.save(ad);
			
			HashMap data = new HashMap();
			writeJson(new Result2(0,"ok",data));
			return null;
		}
		
		writeJson(new Result2(-1,"error","auth验证失败"));
		return null;
	}
	
	
	//激活
	public String activatedApp(){
		
		String auth = getFilterParameter(request, "auth");
		
		ArrayList list = (ArrayList)commonDao.find("from TdAd where authtoken=? ", new Object[]{auth});
		if(list!=null && list.size()>0){
			TdAd ad =(TdAd) list.get(0);
			ad.setState("3");
			commonDao.save(ad);
			
			HashMap data = new HashMap();
			writeJson(new Result2(0,"ok",data));
			return null;
		}
		
		writeJson(new Result2(-1,"error","auth验证失败"));
		return null;
	}
	
	
	//激活-详情
	public String activatedAppType(){
			
			String auth = getFilterParameter(request, "auth");
			String activeType = getFilterParameter(request, "activeType");
			if("".equals(activeType)){
				writeJson(new Result2(-1,"error","activeType不能为空"));
				return null;
			}
			
			ArrayList list = (ArrayList)commonDao.find("from TdAd where authtoken=? and state=3 ", new Object[]{auth});
			if(list!=null && list.size()>0){
				TdAd ad =(TdAd) list.get(0);
				ad.setActiveType(activeType);
				commonDao.save(ad);
				
				HashMap data = new HashMap();
				data.put("type", activeType);
				writeJson(new Result2(0,"ok",data));
				return null;
			}
			
			writeJson(new Result2(-1,"error","auth验证失败"));
			return null;
		}
		
	
	
	
	protected final String getFilterParameter(HttpServletRequest request,String key) 
	 {
		return StringUtils.trimToEmpty(request.getParameter(key)) ;
	 }
	
	
	
	
	///////////////////////////////////////// 以下方法是给张敏杰临时用的 end
	
	
	
	
	
	
	

	public CommonDao getCommonDao()
	{
		return commonDao;
	}

	public void setCommonDao(CommonDao commonDao)
	{
		this.commonDao = commonDao;
	}

	public List<DevUsers> getDevUserList()
	{
		return devUserList;
	}

	public void setDevUserList(List<DevUsers> devUserList)
	{
		this.devUserList = devUserList;
	}

	public UserService getUserService()
	{
		return userService;
	}

	public void setUserService(UserService userService)
	{
		this.userService = userService;
	}

	public String login() {
		
		String username = vo.getDevname();
		String password = vo.getDevpasswd();
		boolean check = false;
		if ((username == null || username.length() == 0)
				&& (password == null || password.length() == 0)) {
			check = false;
		}
		
		HashMap map = new HashMap();

		try {
			vo = userService.getUserByNameAndPassword(username,EncryptUtil.encrypt(password));
			check = true;
		} catch (Exception e) {
			check = false;
		}
		if (check) {
			
			vo.setLogintime(vo.getLasttime()); //取上次登录时间
			vo.setLasttime(new Date());
			commonDao.save(vo);
			
			HashMap map1 =  new HashMap();
			map1.put("Id", vo.getDevid());
			map1.put("type", "1");
			
			
			session.put("user", vo);
			
			return SUCCESS;
		} else {
			return "login";
//			this.setMessage("用户或者密码错误");
//			this.addActionError("用户或者密码错误");
//			setLocalationURL(this.getBasePath()+ IBasicAction.Struts2FilterFold + "/login.jsp");
//			return IBasicAction.RedirectionLoaction;
		}
	}
	
	/**
	 * 注册开发者
	 * @return
	 */
	public String insert(){
		DevUsers vo = new DevUsers();
		String name = this.request.getParameter("vo.devname");
		String pwd = this.request.getParameter("vo.devpasswd");
		String phone = this.request.getParameter("vo.phonenum");
		int ret = AppUtils.checkUserName(name);
		if(ret!=0){
			if(ret==-1){
				writeJson(new Result(-1,"帐号为空"));
				return null;
			}else if(ret==-2){
				writeJson(new Result(-2,"帐号只能以字母开头"));
				return null;
			}else if(ret==-3){
				writeJson(new Result(-3,"帐号长度为6-20个字符"));
				return null;
			}else if(ret==-4){
				writeJson(new Result(-4,"帐号由数字,字母或下划线组成,并只能以字母开头,字母和数字结尾"));
				return null;
			}
		}
		if(!userService.hasUserByName(name)){
			writeJson(new Result(-5,"该帐号已存在"));
			return null;
		}
		try{
			vo.setDevname(name);
			vo.setDevpasswd(EncryptUtil.encrypt(pwd));
			vo.setRegip(request.getRemoteHost());
			vo.setCreatetime(new Date());
			vo.setLasttime(new Date());
			vo.setLogintime(new Date());
			vo.setStatus(new Byte("0"));
			vo.setType(0L);
			vo.setTokenring("");
			vo.setPhonenum(phone);
			userService.save(vo);
			writeJson(new Result(0,"ok"));
		}catch(Exception e){
			e.printStackTrace();
			writeJson(new Result(-100,"操作失败，请稍候再试"));
		}
		return null;
	}
	
	/**
	 * 开发者列表
	 * @return
	 */
	public String select(){
		
		Map map = new HashMap();
		if( request.getParameter("vo.devname")!=null&&!"".equals( request.getParameter("vo.devname"))){
			map.put("devname", request.getParameter("vo.devname"));
		}
		
		Page page = commonDao.pagedQueryByMap(DevUsers.class,gotoPage, pageSize,map);
		devUserList = (List<DevUsers>)page.getResult();
		this.setPageInfo(page);
		return SUCCESS;
	}
	
	
	public String delete(){
		try{
			commonDao.removeById(DevUsers.class,Integer.parseInt(request.getParameter("id")));
			writeJson(new Result(0,"ok"));
		}catch(Exception e){
			writeJson(new Result(-1,"操作失败,该数据被其他引用"));
		}
		return null;
	}
	
	
	public String logout(){
		session.clear();
		writeJson(new Result(0,"ok"));
		return null;
	}
	

	public DevUsers getVo()
	{
		return vo;
	}

	public void setVo(DevUsers vo)
	{
		this.vo = vo;
	}

	
	
	
}
